package stack

import (
	"fmt"
	"strings"
)

// 顺序存储的栈--顺序栈

type SequenceStack struct {
	Len      int
	TopIndex int
	Stack    []interface{}
}

func NewSequenceStack(slen int) *SequenceStack {
	return &SequenceStack{
		Len:      slen,
		TopIndex: -1,
		Stack:    make([]interface{}, slen),
	}
}

func (ss *SequenceStack) IsEmpty() bool {
	return ss.TopIndex == -1
}

func (ss *SequenceStack) PushStack(x interface{}) {
	if ss.TopIndex > ss.Len-1 {
		fmt.Println("栈满")
		return
	}
	ss.TopIndex++
	ss.Stack[ss.TopIndex] = x
}

func (ss *SequenceStack) TravelSequenceStack() {
	if ss.IsEmpty() {
		fmt.Println("栈为空")
		return
	}
	stackStr := ""
	for _, v := range ss.Stack {
		if v != nil {
			stackStr += fmt.Sprintf("%v, ", v)
		}
	}
	stackStr = strings.TrimRight(stackStr, ", ")
	fmt.Printf("遍历当前栈元素(栈底->栈顶)： [%s]\n", stackStr)
}

func (ss *SequenceStack) PopStack() interface{} {
	if ss.IsEmpty() {
		fmt.Println("栈为空")
		return nil
	}
	topElement := ss.Stack[ss.TopIndex]
	ss.Stack[ss.TopIndex] = nil
	ss.TopIndex--
	return topElement
}

func (ss *SequenceStack) GetTopStack() interface{} {
	if ss.IsEmpty() {
		return nil
	}
	return ss.Stack[ss.TopIndex]
}
